package com.iv.durian.cloud.filter;

import com.iv.durian.cloud.User;
import com.iv.durian.cloud.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//@Component
//@WebFilter(urlPatterns = "/api/*",filterName = "accessTokenFilter")
public class AccessTokenFilter implements Filter {
    @Autowired
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String accessToken = request.getParameter("access_toke");
        if (StringUtils.isBlank(accessToken)){
            throw new IllegalArgumentException("access_toke is required");
        }

        User user = userService.getUserByAccessToken(accessToken);
        if (user == null){
            throw new IllegalArgumentException("not find user by accessToken");
        }
        if (user.getExpire() < System.currentTimeMillis()){
            throw new IllegalArgumentException("accessToken is expire");
        }
    }

    @Override
    public void destroy() {

    }
}
